package com.mes.cloud.quartz;

import com.mes.cloud.dto.QuartzTaskDTO;
import com.mes.cloud.service.QuartzTaskService;
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @Description TODO
 * @author: wxm
 * @date: 2019/6/10 15:32
 * @version: 1.0
 */
@Component
public class QuartzPlugin implements IPlugin{
    /**
     * 日志记录
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(QuartzPlugin.class);

    private SchedulerFactory sf = null;

    public static Scheduler scheduler = null;

    @Autowired
    private QuartzTaskService quartzTaskService ;

    /**
     * 启动Quartz
     */
    @Override
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public boolean start() {
        // 创建调度工厂
        sf = new StdSchedulerFactory();

        try {
            scheduler = sf.getScheduler();

            List<QuartzTaskDTO> tasks = quartzTaskService.getQuartzTaskListAll();
            for (QuartzTaskDTO task : tasks) {
                String jobClassName = task.getClazz();
                String jobCronExp = task.getExp();
                int state = task.getState();

                Class clazz;
                try {
                    clazz = Class.forName(jobClassName);
                } catch (ClassNotFoundException e) {
                    throw new RuntimeException(e);
                }

                JobDetail job = JobBuilder.newJob(clazz).withIdentity(jobClassName, jobClassName).build();
                // job.getJobDataMap().put("type", "eova");
                CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(jobClassName, jobClassName).withSchedule(CronScheduleBuilder.cronSchedule(jobCronExp)).build();

                try {
                    scheduler.scheduleJob(job, trigger);
                    if (state == QuartzTaskDTO.STATE_STOP) {
                        // 暂停触发
                        scheduler.pauseTrigger(trigger.getKey());
                    }
                } catch (SchedulerException e) {
                    new RuntimeException(e);
                }

                LOGGER.info(job.getKey() + " loading and exp: " + trigger.getCronExpression());
            }

            scheduler.start();

        } catch (SchedulerException e) {
            new RuntimeException(e);
        }

        return true;

    }

    /**
     * 停止Quartz
     */
    @Override
    public boolean stop() {
        try {
            scheduler.shutdown();
        } catch (SchedulerException e) {
            LOGGER.error("shutdown error", e);
            return false;
        }
        return true;
    }


}
